package com.ptszyxx.popose.common.utils.sensitive;

import android.util.Log;
import com.alibaba.fastjson.JSON;
import com.ptszyxx.popose.common.constants.AppConstant;
import com.ptszyxx.popose.common.utils.YBusUtil;
import com.ysg.base.BaseViewModel;
import com.ysg.http.BaseResponse;
import com.ysg.http.DownLoadManager;
import com.ysg.http.HttpUtils;
import com.ysg.http.callback.OnSuccessResult;
import com.ysg.http.data.ApiService;
import com.ysg.http.data.CommonRepository;
import com.ysg.http.data.download.ProgressCallBack;
import com.ysg.utils.YBusBaseUtil;
import com.ysg.utils.YDbUtils;
import com.ysg.utils.YSPUtils;
import com.ysg.utils.YUserUtil;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 敏感词工具类
 */
public class YSensitiveUtil {
    private static SensitiveEntity entity;

    public static String checkSensitiveContent(String content){
        if (null != entity){
            //敏感词数组
            String[] contentArray = entity.getContent();
            if (contentArray != null && contentArray.length > 0){
                for(String item: contentArray){
                    if (content != null && content.contains(item)){
                        return item;
                    }
                }
            }

            //正则
            String[] regexArray = entity.getRegex();
            if (regexArray != null && regexArray.length > 0){
                for(String regex: regexArray){
                    try {
                        Pattern pattern = Pattern.compile(regex);
                        Matcher matcher = pattern.matcher(content);
                        while (matcher.find()) {
                            return matcher.group();
                        }
                    }catch (Exception e){
                    }
                }
            }
        }else{
            parseFile(content);
        }
        return "";
    }

    private static void parseFile(String content) {
        File file = new File(AppConstant.sensitive_dir_name, AppConstant.sensitive_file_name);
        if (file.exists()){
            StringBuilder sb = new StringBuilder();
            FileInputStream inputStream;
            try {
                inputStream = new FileInputStream(file);
                InputStreamReader isr = new InputStreamReader(inputStream);
                BufferedReader reader = new BufferedReader(isr);
                String jsonLine;
                while ((jsonLine = reader.readLine()) != null) {
                    sb.append(jsonLine);
                }
                reader.close();
                isr.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            String str =  sb .toString();
            entity = JSON.parseObject(str, SensitiveEntity.class);
            if (null != entity){
                checkSensitiveContent(content);
            }
        }else{
            onDownloadSensitiveFile();
        }
    }

    /**
     * 敏感词文件下载
     */
    public static void onDownloadSensitiveFile() {
        DownLoadManager.getInstance().load(ApiService.sensitive_url, false, new ProgressCallBack(AppConstant.sensitive_dir_name, AppConstant.sensitive_file_name) {
            @Override
            public void onSuccess(Object o) {
                Log.e("下载成功", "神功");
            }

            @Override
            public void progress(long progress, long total) {
                Log.e("下载progress", "progress");
            }

            @Override
            public void onError(Throwable e) {
                Log.e("下载onError", "onError");
            }
        });

    }

    /**
     * 保存发送敏感词记录
     */
    public static void save(BaseViewModel viewModel, CommonRepository repository, String input, String sensitives){
        String userId = YSPUtils.getInstance().getUserId();
        YDbUtils.getInstance().saveUserSensitive(input, sensitives);

        //封号
        boolean than = YDbUtils.getInstance().isThanCountByUserSensitive(userId + "");
        if (than){
            requestUpdateUserState(viewModel, repository);
        }
    }

    /**
     * 封号：男号封3天；女号永久封号
     */
    private static void requestUpdateUserState(BaseViewModel viewModel, CommonRepository repository) {
        String hour = (3 * 24) + "";
        String userId = YSPUtils.getInstance().getUserId();
        if (YUserUtil.isGirl()){
            hour = "-1";//女号
        }

        Map<String, String> map = new HashMap<>();
        map.put("userId", userId);
        map.put("state", "2");
        map.put("hour", hour);
        HttpUtils.getInstance()
                .data(repository.userDelete(map), viewModel,
                        new OnSuccessResult() {
                            @Override
                            public void onSuccessResult(BaseResponse response) {
                                YDbUtils.getInstance().deleteUserSensitive(userId+"");
                                YBusBaseUtil.logout();
                            }
                        });
    }

}
